package com.yupi.moonBI.utils;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
/**
 * Excel相关工具类
 */
public class ExcelUtils {

    /**
     * excel转csv
     *
     * @param multipartFile
     * @return
     */
    public static String excelToCsv(MultipartFile multipartFile)throws FileNotFoundException{
        //File file=null;
        //try {
        //    file = ResourceUtils.getFile("classpath:网站数据.xlsx");
        //} catch (FileNotFoundException e) {
        //    e.printStackTrace();
        //}
        //使用真实文件
        //每个Map代表一行数据，Integer是列索引（从0开始），String是单元格值。
        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)// 指定处理XLSX格式文件
                    .sheet()// 读取第一个Sheet
                    .headRowNumber(0)// 将第1行（索引0）作为表头
                    .doReadSync();
        } catch (IOException e) {
            log.error("excel转换错误", e);
            throw new RuntimeException("excel转换错误");
        }
        if (CollUtil.isEmpty(list)) {
            return "";
        }

        //转换成csv
        StringBuilder stringBuilder = new StringBuilder();
        //读取表头
        LinkedHashMap<Integer, String> headerMap = (LinkedHashMap) list.get(0);
        List<String> headerList = headerMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
        stringBuilder.append(StringUtils.join(headerList, ",")).append("\n");

        //读取数据
        for (int i = 1; i < list.size(); i++) {
            LinkedHashMap<Integer, String> dataMap = (LinkedHashMap) list.get(i);
            List<String> dataList = dataMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
            stringBuilder.append(StringUtils.join(dataList, ",")).append("\n");
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) throws FileNotFoundException {
        excelToCsv(null);
    }
}
